package org.breathe.dynamic.thread.pool.core.reject;

import lombok.extern.slf4j.Slf4j;
import org.breathe.thread.pool.common.enums.RejectedTypeEnum;
import org.breathe.thread.pool.common.exception.DtpException;

import java.lang.reflect.Proxy;
import java.util.ServiceLoader;
import java.util.concurrent.RejectedExecutionHandler;

/**
 * 获取拒绝策略
 * @author: breathe
 * @createTime: 2025-04-09
 */
@Slf4j
public class RejectHandlerGetter {
    private RejectHandlerGetter() {}

    public static RejectedExecutionHandler buildRejectedHandler(String name) {
        for (RejectedTypeEnum rejectedTypeEnum : RejectedTypeEnum.values()) {
            if (rejectedTypeEnum.getName().equals(name)) {
                return rejectedTypeEnum.getHandler();
            }
        }
        ServiceLoader<RejectedExecutionHandler> serviceLoader = ServiceLoader.load(RejectedExecutionHandler.class);
        for (RejectedExecutionHandler handler : serviceLoader) {
            String handlerName = handler.getClass().getSimpleName();
            if (name.equalsIgnoreCase(handlerName)) {
                return handler;
            }
        }
        log.error("can't find this rejectedHandler {}", name);
        throw new DtpException("can't find this rejectedHandler " + name);
    }

    public static RejectedExecutionHandler getProxy(String name) {
        return getProxy(buildRejectedHandler(name));
    }

    public static RejectedExecutionHandler getProxy(RejectedExecutionHandler handler) {
        return (RejectedExecutionHandler) Proxy
                .newProxyInstance(handler.getClass().getClassLoader(),
                        new Class[]{RejectedExecutionHandler.class},
                        new RejectedInvocationHandler(handler));
    }
}